//
//  LFBReadDetailView.m
//  ONE
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LFBReadDetailView.h"
#import "LFBNetTool.h"
#import "LYLChargeEditorView.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "LYLNoneMessageCell.h"
#import <YYText.h>
#import "LYLCommentCell.h"
#import "LYLCommentListModel.h"
#import "MZSelectableLabel.h"
#import "BaseViewController.h"
#import "LFBReadShortModel.h"
#import "LFBReadShortDetailModel.h"
#import "LFBReadSerialModel.h"
#import "LFBSerialDetailModel.h"
#import "LFBReadQuestionModel.h"
#import "LFBReadQuestionDetailModel.h"
#import "LFBReadBaseCell.h"
#import "LYLCommentListViewController.h"
#import "LFBReadCarouselContentView.h"
#import "LFBSingleReadDetailViewController.h"

NSString *const kLFBReadDetailViewID = @"LFBReadDetailViewID";

@interface LFBReadDetailView () <UITableViewDelegate, UITableViewDataSource>

/** 底部滚动视图 */
@property (nonatomic, strong) UIScrollView *scrollView;

/** 短篇连载内容视图 */
@property (nonatomic, strong) UIView *contentView;

/** 问答视图 */
@property (nonatomic, strong) UIView *questionView;

/** 问答标题 */
@property (nonatomic, strong) UILabel *questionTitleLabel;

/** 问答内容 */
@property (nonatomic, strong) UILabel *questionContentLabel;

/** 作者视图 */
@property (nonatomic, strong) UIView *authorView;

/** 作者头像 */
@property (nonatomic, strong) UIImageView *authorAvatarView;

/** 作者名字 */
@property (nonatomic, strong) UILabel *authorNameLabel;

/** 日期 */
@property (nonatomic, strong) UILabel *dateLabel;

/** 作者介绍 */
@property (nonatomic, strong) UILabel *authorDescLabel;

/** 文章内容中心视图 */
@property (nonatomic, strong) UIView *contentCenterView;

/** 文章标题label */
@property (nonatomic, strong) MZSelectableLabel *titleLabel;

/** 收听按钮 */
@property (nonatomic, strong) UIButton *listenInButton;

/** 文章内容视图 */
@property (nonatomic, strong) YYTextView *contentTextView;

/** 编辑视图 */
@property (nonatomic, strong) LYLChargeEditorView *editorView;

/** 评论列表 */
@property (nonatomic, strong) LYLCommentListViewController *commentListViewController;

/** 相关推荐表视图 */
@property (nonatomic, strong) UITableView *relatedsTableView;

/** 相关推荐头视图 */
@property (nonatomic, strong) LYLCommonHeaderView *relatedsHeaderView;

/** 相关推荐尾视图 */
@property (nonatomic, strong) LYLCommonFooterView *relatedsFooterView;

/** 轮播图内容视图 */
@property (nonatomic, strong) LFBReadCarouselContentView *carouselContentView;

/** 问答视图顶部约束 */
@property (nonatomic, strong) MASConstraint *questionViewTopConstraint;

/** 内容视图高度约束 */
@property (nonatomic, strong) MASConstraint *contentTextViewHeightConstraint;

/** 文章标题视图顶部约束 */
@property (nonatomic, strong) MASConstraint *contentCenterViewTopConstraint;

/** 责任编辑视图高度约束 */
@property (nonatomic, strong) MASConstraint *chargeEditorHeightConstraint;

/** 评论表视图高度约束 */
@property (nonatomic, strong) MASConstraint *commentsTableViewHeightConstraint;

/** 相关推荐表视图高度约束 */
@property (nonatomic, strong) MASConstraint *relatedsTableViewHeightConstraint;

@end

@implementation LFBReadDetailView
{
    /** 文章类型 */
    LYLReadType viewType;
    /** 文章详情数据源 */
    BaseModel *readDetailModel;
    /** 文章数据源 */
    BaseModel *readModel;
    /** 相关推荐数组 */
    NSArray *relatedList;
    /** 相关推荐行高 */
    NSMutableArray *relatedRowsHeight;
}

- (void)dealloc
{
    // 移除评论列表
    [_commentListViewController removeFromParentViewController];
    
    _relatedsTableView.delegate = nil;
    _relatedsTableView.dataSource = nil;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
        [self createDetailView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initData];
        [self createDetailView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self initData];
        [self createDetailView];
    }
    return self;
}

#pragma mark --初始化数据
- (void)initData
{
    relatedRowsHeight = @[].mutableCopy;
}

#pragma mark --创建文章详情视图
- (void)createDetailView
{
    if (_scrollView) {
        return;
    }
    
    self.backgroundColor = [UIColor whiteColor];
    
    // 初始化滚动视图
    _scrollView = [UIScrollView new];
    _scrollView.backgroundColor = LYLViewControllerBGColor;
    [self addSubview:_scrollView];
    [_scrollView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    // 初始化短篇连载内容视图
    _contentView = [UIView new];
    _contentView.backgroundColor = _scrollView.backgroundColor;
    [_scrollView addSubview:_contentView];
    [_contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_scrollView);
        make.width.equalTo(SCREEN_WIDTH);
    }];
    
    // 初始化视图
    _questionView = [UIView new];
    _questionView.backgroundColor = _contentView.backgroundColor;
    [_contentView addSubview:_questionView];
    [_questionView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_contentView);
        _questionViewTopConstraint = make.top.equalTo(_contentView);
    }];
    
    // 初始化问答标题
    _questionTitleLabel = [UILabel new];
    _questionTitleLabel.backgroundColor = _questionView.backgroundColor;
    _questionTitleLabel.textColor = LYLLightBlackTextColor;
    _questionTitleLabel.font = FontWithSize(18);
    _questionTitleLabel.numberOfLines = 0;
    [_questionView addSubview:_questionTitleLabel];
    [_questionTitleLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(_questionView).insets(UIEdgeInsetsMake(17, 12, 0, 12));
    }];
    
    // 初始化问答内容Label
    _questionContentLabel = [UILabel new];
    _questionContentLabel.backgroundColor = _questionView.backgroundColor;
    _questionContentLabel.textColor = LYLLightBlackTextColor;
    _questionContentLabel.font = FontWithSize(15);
    _questionContentLabel.numberOfLines = 0;
    [_questionView addSubview:_questionContentLabel];
    [_questionContentLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_questionTitleLabel);
        make.top.equalTo(_questionTitleLabel.bottom).offset(12);
        make.bottom.equalTo(_questionView).offset(-20);
    }];
    
    // 初始化问答底部横线
    UIView *questionViewBottomLine = [UIView new];
    questionViewBottomLine.backgroundColor = LYLSeparatorColor;
    [_questionView addSubview:questionViewBottomLine];
    [questionViewBottomLine makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(0.5);
        make.left.bottom.right.equalTo(_questionView).insets(UIEdgeInsetsMake(0, 6, 0, 6));
    }];
    
    // 初始化作者视图
    _authorView = [UIView new];
    _authorView.backgroundColor = _contentView.backgroundColor;
    [_contentView addSubview:_authorView];
    [_authorView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_questionView.bottom);
        make.left.right.equalTo(_contentView);
    }];
    
    // 初始化作者头像
    _authorAvatarView = [UIImageView new];
    _authorAvatarView.layer.borderColor = [UIColor whiteColor].CGColor;
    _authorAvatarView.layer.borderWidth = 1;
    _authorAvatarView.layer.cornerRadius = 24;
    _authorAvatarView.clipsToBounds = YES;
    _authorAvatarView.backgroundColor = _authorView.backgroundColor;
    _authorAvatarView.contentMode = UIViewContentModeScaleAspectFill;
    [_authorView addSubview:_authorAvatarView];
    [_authorAvatarView makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(48);
        make.top.equalTo(_authorView).offset(20);
        make.left.equalTo(_authorView).offset(12);
        make.bottom.lessThanOrEqualTo(_authorView).offset(-5);
    }];
    
    // 初始化作者名字
    _authorNameLabel = [UILabel new];
    _authorNameLabel.backgroundColor = _authorView.backgroundColor;
    _authorNameLabel.textColor = LYLAppThemeColor;
    _authorNameLabel.font = FontWithSize(12);
    [_authorView addSubview:_authorNameLabel];
    [_authorNameLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_authorAvatarView).offset(6);
        make.left.equalTo(_authorAvatarView.right).offset(12);
    }];
    
    // 初始化日期
    _dateLabel = [UILabel new];
    _dateLabel.backgroundColor = _authorView.backgroundColor;
    _dateLabel.textColor = LYLLightGrayTextColor;
    _dateLabel.font = FontWithSize(12);
    _dateLabel.textAlignment = 2;
    [_dateLabel setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisHorizontal];
    [_authorView addSubview:_dateLabel];
    [_dateLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_authorNameLabel.right);
        make.top.equalTo(_authorNameLabel);
        make.right.equalTo(_authorView).offset(-12);
    }];
    
    // 初始化作者介绍
    _authorDescLabel = [UILabel new];
    _authorDescLabel.backgroundColor = _authorView.backgroundColor;
    _authorDescLabel.textColor = LYLLightGrayTextColor;
    _authorDescLabel.font = FontWithSize(12);
    _authorDescLabel.numberOfLines = 0;
    [_authorView addSubview:_authorDescLabel];
    [_authorDescLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_authorNameLabel);
        make.top.equalTo(_authorNameLabel.bottom).offset(4);
        make.bottom.lessThanOrEqualTo(_authorView).offset(-5);
    }];
    
    // 初始化文章内容中心视图
    _contentCenterView = [UIView new];
    [_contentView addSubview:_contentCenterView];
    [_contentCenterView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_contentView);
        _contentCenterViewTopConstraint = make.top.equalTo(_authorView.bottom);
    }];
    
    // 初始化文章标题label
    _titleLabel = [MZSelectableLabel new];
    _titleLabel.textColor = LYLLightBlackTextColor;
    _titleLabel.font = FontWithSize(18);
    _titleLabel.numberOfLines = 0;
    // 以字符为单位换行，以字符为单位截断
    _titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [_contentCenterView addSubview:_titleLabel];
    [_titleLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentCenterView).offset(12);
        make.top.equalTo(_contentCenterView).offset(4);
    }];
    
    // 初始化收听按钮
    _listenInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_listenInButton setImage:[UIImage imageNamed:@"audio_normal"] forState:UIControlStateNormal];
    [_listenInButton setImage:[UIImage imageNamed:@"audio_highlighted"] forState:UIControlStateHighlighted];
    [_listenInButton addTarget:self action:@selector(didClickedListenInButton) forControlEvents:UIControlEventTouchUpInside];
    _listenInButton.hidden = YES;
    [_contentCenterView addSubview:_listenInButton];
    [_listenInButton makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(44);
        make.centerY.equalTo(_titleLabel);
        make.left.equalTo(_titleLabel.right).offset(10);
        make.right.equalTo(_contentCenterView).offset(-6);
    }];
    
    // 初始化内容视图
    _contentTextView = [YYTextView new];
    _contentTextView.backgroundColor = LYLViewControllerBGColor;
    _contentTextView.textColor = LYLDarkBlackTextColor;
    _contentTextView.font = FontWithSize(15);
    
    // 设为不可编辑
    _contentTextView.editable = NO;
    _contentTextView.scrollEnabled = NO;
    _contentTextView.showsVerticalScrollIndicator = NO;
    _contentTextView.showsHorizontalScrollIndicator = NO;
    _contentTextView.textContainerInset = UIEdgeInsetsMake(8, 8, 8, 8);
    [_contentCenterView addSubview:_contentTextView];
    [_contentTextView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.bottom).offset(20);
        make.left.bottom.right.equalTo(_contentCenterView).insets(UIEdgeInsetsMake(0, 6, 0, 6));
        _contentTextViewHeightConstraint = make.height.equalTo(0);
    }];
    
    // 初始化编辑视图
    _editorView = [LYLChargeEditorView new];
    _editorView.backgroundColor = LYLViewControllerBGColor;
    _editorView.clipsToBounds = YES;
    [_contentView addSubview:_editorView];
    [_editorView makeConstraints:^(MASConstraintMaker *make) {
        _chargeEditorHeightConstraint = make.height.equalTo(68);
        make.top.equalTo(_contentCenterView.bottom);
        make.left.right.equalTo(_contentView);
    }];
    
    //初始化评论列表
    __weak typeof(self) weakSelf = self;
    _commentListViewController = [[LYLCommentListViewController alloc] initWithCommentListType:LYLCommentListTypeReadComments headerViewType:LYLHeaderViewTypeComment footerViewType:LYLFooterViewTypeComment];
    _commentListViewController.finishedCalculateHeigt = ^(CGFloat height)
    {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.commentsTableViewHeightConstraint.equalTo(height);
    };
    [_contentView addSubview:_commentListViewController.tableView];
    [_commentListViewController.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_editorView.bottom);
        make.left.right.equalTo(_contentView);
        _commentsTableViewHeightConstraint = make.height.equalTo(0);
    }];
    
    // 初始化相关推荐表视图
    _relatedsTableView = [UITableView new];
    _relatedsTableView.backgroundColor = [UIColor whiteColor];
    _relatedsTableView.dataSource = self;
    _relatedsTableView.delegate = self;
    _relatedsTableView.scrollEnabled = NO;
    [_relatedsTableView registerClass:[LFBReadBaseCell class] forCellReuseIdentifier:kLFBReadBaseCellID];
    _relatedsTableView.tableFooterView = [UIView new];
    _relatedsTableView.separatorInset = UIEdgeInsetsMake(0, 54, 0, 6);
    _relatedsTableView.separatorColor = LYLSeparatorColor;
    [_contentView addSubview:_relatedsTableView];
    [_relatedsTableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_commentListViewController.tableView.bottom).offset(5);
        make.left.right.equalTo(_contentView);
        make.bottom.equalTo(_contentView).offset(-12);
        _relatedsTableViewHeightConstraint = make.height.equalTo(0);
    }];
}

#pragma mark --准备更新视图
- (void)preUpdateView
{
    if (viewType == LYLReadTypeQuestion) {
        return;
    }
    // 标记为需要重新布局，异步调用layoutIfNeeded刷新布局，不立即刷新，但layoutSubviews一定会被调用 如果要立即刷新，要先调用[view setNeedsLayout]，把标记设为需要布局，然后马上调用[view layoutIfNeeded]，实现布局

    [_questionView setNeedsLayout];
    _questionTitleLabel.text = @"ONE";
    _questionContentLabel.text = @"one";
    
    // 如果，有需要刷新的标记，立即调用layoutSubviews进行布局（如果没有标记，不会调用layoutSubviews）在视图第一次显示之前，标记总是“需要刷新”的，可以直接调用[view layoutIfNeeded]
    [_questionView layoutIfNeeded];
    _questionViewTopConstraint.offset((CGRectGetHeight(_questionView.frame) * -1));
    _questionView.hidden = YES;
    
    _titleLabel.text = @"";
    _authorAvatarView.image = [UIImage imageNamed:@"personal"];
    _authorNameLabel.text = @"";
    _authorDescLabel.text = @"";
    _dateLabel.text = @"";
    
    _contentTextViewHeightConstraint.equalTo(0);
    _chargeEditorHeightConstraint.equalTo(0);
    _commentsTableViewHeightConstraint.equalTo(0);
    _relatedsTableViewHeightConstraint.equalTo(0);
}

#pragma mark --更新作者视图
- (void)updateAuthorView
{
    LYLAuthorItemModel *author;
    NSString *dataString;
    if (viewType == LYLReadTypeShort) {
        LFBReadShortModel *model = (LFBReadShortModel *)readModel;
        author = [model.author firstObject];
        dataString = model.hp_makettime;
        _titleLabel.text = model.hp_title;
    }
    else
    {
        LFBReadSerialModel *model = (LFBReadSerialModel *)readModel;
        author = model.model;
        dataString = model.maketime;
        NSString *numberString = [NSString stringWithFormat:@"( %@ )", model.number];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@", model.title, numberString] attributes:@{NSForegroundColorAttributeName : _titleLabel.textColor, NSFontAttributeName : _titleLabel.font}];
        NSRange numberStringRange = [attributedString.string rangeOfString:numberString];
        [attributedString addAttributes:@{NSForegroundColorAttributeName : LYLAppThemeColor} range:numberStringRange];
        [attributedString addAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]} range:NSMakeRange(0, numberStringRange.location)];
        _titleLabel.attributedText = attributedString;
        [_titleLabel.selectableRanges removeAllObjects];
        [_titleLabel setSelectableRange:numberStringRange hightlightedBackgroundColor:LYLAppThemeColor];
        __weak typeof(self) weakSelf = self;
        _titleLabel.selectionHandler = ^(NSRange range, NSString *string)
        {
            [weakSelf didClickedTitleNumber];
        };
    }
    
    [_authorAvatarView sd_setImageWithURL:[NSURL URLWithString:author.web_url] placeholderImage:[UIImage imageNamed:@"personal"]];
    _authorNameLabel.text = author.user_name;
    _authorDescLabel.text = author.desc;
    
    
//    _dateLabel.text =
    
    
}

#pragma mark --contentId
- (NSString *)contentId
{
    return (viewType == LYLReadTypeShort ? ((LFBReadShortModel *)readModel).content_id : (viewType == LYLReadTypeSerial ? ((LFBReadSerialModel *)readModel).id : ((LFBReadQuestionModel *)readModel).question_id));
}

#pragma mark --更新视图
- (void)updateView
{
    if (viewType != LYLReadTypeQuestion) {
        if (viewType == LYLReadTypeShort && IsStringEmpty(((LFBReadShortModel *)readModel).hp_title)) {
            LFBReadShortModel *shortModel = (LFBReadShortModel *)readModel;
            LFBReadShortDetailModel *shortDetailModel = (LFBReadShortDetailModel *)readDetailModel;
            shortModel.hp_title = shortDetailModel.hp_title;
            shortModel.hp_makettime = shortDetailModel.hp_makettime;
            shortModel.guide_word = shortDetailModel.guide_word;
            shortModel.author = shortDetailModel.author;
        }
        else if (viewType == LYLReadTypeSerial && (((LFBReadSerialModel *)readModel).title))
        {
            LFBReadSerialModel *serialModel = (LFBReadSerialModel *)readModel;
            LFBSerialDetailModel *serialDetailModel = (LFBSerialDetailModel *)readDetailModel;
            serialModel.title = serialDetailModel.title;
            serialModel.excerpt = serialDetailModel.excerpt;
            serialModel.read_num = serialDetailModel.read_num;
            serialModel.maketime = serialDetailModel.maketime;
            serialModel.author = serialDetailModel.author;
        }
        
        [self updateAuthorView];
    }
    
    NSString *chargeEditor = @"";
    NSInteger praiseNum = 0;
    switch (viewType) {
        case LYLReadTypeShort:
        {
            LFBReadShortDetailModel *shortDetailModel = (LFBReadShortDetailModel *)readDetailModel;
            [self updateContentTextViewWithText:shortDetailModel.hp_content];
            _listenInButton.hidden = IsStringEmpty(shortDetailModel.audio);
            chargeEditor = shortDetailModel.hp_author_introduce;
            praiseNum = shortDetailModel.praisenum;
            break;
        }
        case LYLReadTypeSerial:
        {
            LFBSerialDetailModel *serialDetailModel = (LFBSerialDetailModel *)readDetailModel;
            [self updateContentTextViewWithText:serialDetailModel.content];
            
            chargeEditor = serialDetailModel.charge_edt;
            praiseNum = serialDetailModel.praisenum;
            break;
        }
        case LYLReadTypeQuestion:
        {
            LFBReadQuestionDetailModel *questionDetailModel = (LFBReadQuestionDetailModel *)readDetailModel;
            _questionTitleLabel.text = questionDetailModel.question_title;
            _questionContentLabel.text = questionDetailModel.question_content;
            _titleLabel.text = questionDetailModel.answer_title;
            
            
//            _dateLabel.text =
            
            [self updateContentTextViewWithText:questionDetailModel.answer_content];
            chargeEditor = questionDetailModel.charge_edt;
            praiseNum = questionDetailModel.praisenum;
            break;
        }
        default:
            break;
    }
    
//    __weak typeof(self) weakSelf = self;
    _chargeEditorHeightConstraint.equalTo(68);
    [_editorView configureViewWithEditorText:chargeEditor praiseNum:praiseNum praiseBlock:^{
        DDLogDebug(@"praise");
    } moreBlock:^{
        
        
//        [weakSelf.parentViewController showPo];
        
        
    }];
    
    [_commentListViewController configureViewForReadDetailWithReadType:viewType itemId:[self contentId]];
    [self.parentViewController addChildViewController:_commentListViewController];
    [_commentListViewController getData];
    [self getRelatedData];
}

#pragma mark --文章内容视图
- (void)updateContentTextViewWithText:(NSString *)text {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding]
                                                                                          options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
                                                                               documentAttributes:nil
                                                                                            error:nil];
    
    attributedString.yy_font = _contentTextView.font;
    attributedString.yy_color = _contentTextView.textColor;
    attributedString.yy_lineSpacing = 10;
    
    
    _contentTextView.attributedText = attributedString;
    _contentTextViewHeightConstraint.equalTo(@(_contentTextView.textLayout.textBoundingSize.height));

}

#pragma mark --更新相关推荐表视图
- (void)updateRelatedsTableView
{
    CGFloat tableViewHeight = 0;
    if (relatedList.count > 0) {
        tableViewHeight = [LYLCommonHeaderView headerViewHeight] + [LYLCommonFooterView footerViewHeightForShadow];
        [relatedRowsHeight removeAllObjects];
        for (BaseModel *model in relatedList) {
            CGFloat cellHeight = [_relatedsTableView fd_heightForCellWithIdentifier:kLFBReadBaseCellID configuration:^(LFBReadBaseCell *cell) {
                [cell configureCellWithBaseModel:model];
            }];
            [relatedRowsHeight addObject:@(ceil(cellHeight))];
            tableViewHeight += ceil(cellHeight);
        }
    }
    
    _relatedsTableViewHeightConstraint.equalTo(@(ceil(tableViewHeight)));
    [_relatedsTableView reloadData];
}

#pragma mark --收听按钮点击方法
- (void)didClickedListenInButton
{
    NSLog(@"qwer");
}

#pragma mark --轮播图内容标题数字点击方法
- (void)didClickedTitleNumber
{
    if (!_carouselContentView) {
        _carouselContentView = [[LFBReadCarouselContentView alloc] init];
        __weak typeof(self) weakSelf = self;
        _carouselContentView.didSelectedSerial = ^(LFBReadSerialModel *model)
        {
            [weakSelf.carouselContentView dismissWithCompleted:^{
                [weakSelf showSingleReadDetailWithReadModel:model];
            }];
        };
    }
    
    _carouselContentView.serialModel = (LFBReadSerialModel *)readModel;
    [_carouselContentView show];
}

#pragma mark --显示单个的阅读详情
- (void)showSingleReadDetailWithReadModel:(BaseModel *)model
{
    LFBSingleReadDetailViewController *singleReadDetailViewController = [[LFBSingleReadDetailViewController alloc] init];
    singleReadDetailViewController.readType = viewType;
    singleReadDetailViewController.readModel = model;
    [self.parentViewController.navigationController pushViewController:singleReadDetailViewController animated:YES];
}

#pragma mark --网络请求
- (void)getDetailData
{
    [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiGetReadDetails, [LFBNetTool apiStringForReadDetailsWithReadType:viewType], [self contentId]] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        NSLog(@"%@", [self contentId]);
        if ([result[@"res"] integerValue] == 0) {
            NSDictionary *data = result[@"data"];
            BaseModel *detailModel;
            switch (viewType) {
                case LYLReadTypeShort:
                {
                                           LFBReadShortDetailModel *shortDModel = [[LFBReadShortDetailModel alloc] initWithDic:data];
                        detailModel = shortDModel;
                    break;
                }
                case LYLReadTypeSerial:
                {
                        LFBSerialDetailModel *serialDModel = [[LFBSerialDetailModel alloc] initWithDic:data];
                        detailModel = serialDModel;
                    break;
                }
                case LYLReadTypeQuestion:
                {
                        LFBReadQuestionDetailModel *questionDModel = [[LFBReadQuestionDetailModel alloc] initWithDic:data];
                        detailModel = questionDModel;
                    break;
                }
                default:
                    break;
            }
            
            readDetailModel = detailModel;
            [self updateView];
        }
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark --请求相关推荐数据
- (void)getRelatedData
{
    [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiGetRelateds,[LFBNetTool apiStringForReadWithReadType:viewType], [self contentId]] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue] == 0) {
            NSMutableArray *results = [NSMutableArray array];
            NSArray *data = result[@"data"];
            switch (viewType) {
                case LYLReadTypeShort:
                {
                    for (NSDictionary *dic in data) {
                        LFBReadShortModel *shortModel = [[LFBReadShortModel alloc] initWithDic:dic];
                        [results addObject:shortModel];
                    }
                    break;
                }
                case LYLReadTypeSerial:
                {
                    for (NSDictionary *dic in data) {
                        LFBReadSerialModel *serialModel = [[LFBReadSerialModel alloc] initWithDic:dic];
                        [results addObject:serialModel];
                    }
                    break;
                }
                case LYLReadTypeQuestion:
                {
                    for (NSDictionary *dic in data) {
                        LFBReadQuestionModel *questionModel = [[LFBReadQuestionModel alloc] initWithDic:dic];
                        [results addObject:questionModel];
                    }
                    break;
                }
                default:
                    break;
            }
            relatedList = results;
            [self updateRelatedsTableView];
        }
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark --准备重用
- (void)prepareForReuseWithViewType:(LYLReadType)type
{
    _listenInButton.hidden = YES;
    
    if (type == LYLReadTypeQuestion) {
        _contentCenterViewTopConstraint.offset(-55);
    }
    else
    {
        _authorAvatarView.image = [UIImage imageNamed:@"personal"];
        _authorNameLabel.text = @"";
        _authorDescLabel.text = @"";
        _titleLabel.text = @"";
        _dateLabel.text = @"";
    }
    
    _contentTextViewHeightConstraint.equalTo(0);
    _chargeEditorHeightConstraint.equalTo(0);
    _commentsTableViewHeightConstraint.equalTo(0);
    _relatedsTableViewHeightConstraint.equalTo(0);
}

#pragma mark --设置带有父视图控制器的视图
- (void)configureViewWithReadModel:(BaseModel *)model type:(LYLReadType)type atIndex:(NSInteger)index inViewController:(BaseViewController *)parentViewController
{
    self.viewIndex = index;
    self.parentViewController = parentViewController;
    viewType = type;
    readModel = model;
    [self preUpdateView];
    [self getDetailData];
}

#pragma mark --UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return relatedList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:kLFBReadBaseCellID forIndexPath:indexPath];
}

#pragma mark --UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [LYLCommonHeaderView headerViewHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return [LYLCommonFooterView footerViewHeightForShadow];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [relatedRowsHeight[indexPath.row] floatValue];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (!_relatedsHeaderView) {
        _relatedsHeaderView = [[LYLCommonHeaderView alloc] initWithHeaderViewType:LYLHeaderViewTypeRelatedRec];
    }
    
    return _relatedsHeaderView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (_relatedsFooterView) {
        _relatedsFooterView = [[LYLCommonFooterView alloc] initWithFooterViewType:LYLFooterViewTypeShadow];
    }
    
    return _relatedsFooterView;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [(LFBReadBaseCell *)cell configureCellWithBaseModel:relatedList[indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self showSingleReadDetailWithReadModel:relatedList[indexPath.row]];
}

@end
